package coffee.tigase.client;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

import android.content.ContentValues;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.TextView;
import coffee.base.activity.BasicActivity;
import coffee.provider.AppContentProvider;

public class MainActivity extends BasicActivity {

	private String TAG = "MainActivity";

	// 聊天列表
	private ListView mListView;
	// 聊天内容的Cursor
	private Cursor mCursor;
	// 聊天适配器
	private CursorAdapter mCursorAdapter;
	// 发送按钮
	private Button mSendBtn;

	private TextView mContentText;

	private Chat mChat;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat);

		final Uri uriInsertUser = Uri.parse("content://"
				+ AppContentProvider.AUTH_ORITIES + "/insert/msg_history");

		this.mListView = (ListView) this.findViewById(R.id.chat_list);
		this.mSendBtn = (Button) this.findViewById(R.id.chat_send);
		this.mContentText = (TextView) this.findViewById(R.id.chat_content);

		this.mSendBtn.setOnClickListener(new View.OnClickListener() {

			/**
			 * 发送信息
			 */
			@Override
			public void onClick(View v) {
				ContentValues cv = new ContentValues();
				cv.put("message", mContentText.getText().toString());
				getContentResolver().insert(uriInsertUser, cv);

				try {
					mChat.sendMessage(mContentText.getText().toString());
				} catch (XMPPException e) {
					e.printStackTrace();
				}

				mContentText.setText("");
			}
		});

		this.mCursor = getContentResolver().query(
				Uri.parse("content://" + AppContentProvider.AUTH_ORITIES
						+ "/query/msg_history"), null, null, null, null);

		mCursorAdapter = new ChatCursorAdapter(this, mCursor);

		this.mListView.setAdapter(this.mCursorAdapter);

		this.getContentResolver().registerContentObserver(uriInsertUser, false,
				new ContentObserver(null) {
					@Override
					public void onChange(boolean selfChange) {
						mCursor.requery();
						// 滚动到最后
						mListView.setSelection(mCursor.getCount() - 1);
					}
				});

		new AsyncTask<Void, Void, Void>() {

			@Override
			protected Void doInBackground(Void... params) {
				// 连接xmpp server
				ConnectionConfiguration config = new ConnectionConfiguration(
						"192.168.1.126", 5222, "android");
				//config.setSASLAuthenticationEnabled(false);
				XMPPConnection conn = new XMPPConnection(config);

				try {
					//
					//SASLAuthentication.supportSASLMechanism("PLAIN", 0);
					conn.connect();
					//not-authorized(401) Authorization failed
					//not-authorized(401) Illegal characters in string.
					conn.login("2166399@android", "000000");

					mChat = conn.getChatManager().createChat("2166401@android",
							new MessageListener() {

								@Override
								public void processMessage(Chat chat,
										Message message) {
									System.out.println("Received message: "
											+ message);
									System.out.println(message.getBody());
								}
							});

					Log.d(TAG, "登陆成功");
				} catch (XMPPException e) {
					e.printStackTrace();
				}
				return null;
			}

		}.execute();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				mListView.setSelection(mCursor.getCount() - 1);
			}
		}, 200);
	}

	private class ChatCursorAdapter extends CursorAdapter {

		public ChatCursorAdapter(Context context, Cursor c) {
			super(context, c);
		}

		@Override
		public void bindView(View view, Context context, Cursor cursor) {
			TextView content = (TextView) view.findViewById(R.id.chat_content);
			content.setText(cursor.getString(cursor
					.getColumnIndexOrThrow("message")));
		}

		@Override
		public View newView(Context context, Cursor cursor, ViewGroup parent) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View view = inflater.inflate(R.layout.chat_item, parent, false);
			return view;
		}
	};
}
